package com.shangxian.giveithome.service.impl;


import com.shangxian.giveithome.code.CommonCode;
import com.shangxian.giveithome.code.MechanismCode;
import com.shangxian.giveithome.controller.ImgFeiServer;
import com.shangxian.giveithome.controller.UserFeiController;
import com.shangxian.giveithome.entity.*;
import com.shangxian.giveithome.exception.ExceptionUtils;
import com.shangxian.giveithome.mapper.MechanismDataMapper;
import com.shangxian.giveithome.mapper.MechanismMapper;
import com.shangxian.giveithome.service.MechanismService;
import com.shangxian.giveithome.service.PetService;
import com.shangxian.giveithome.service.VolunteerService;
import com.shangxian.giveithome.utils.IGenerator;
import com.shangxian.giveithome.utils.PageUtils;
import com.shangxian.giveithome.utils.RedisUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import static com.shangxian.giveithome.entity.MechanismDataUp.VolunteerUntreated;


@Service
public class MechanismServiceImpl<T, Z> implements MechanismService {

    @Resource
    private MechanismMapper mechanismMapper;

    @Resource
    private ImgFeiServer imgFeiServer;

    @Autowired
    private IGenerator iGenerator;

    @Autowired
    private RedisUtils redisUtils;

    @Resource
    private UserFeiController userFeiController;

    @Resource
    private MechanismDataMapper mechanismDataMapper;

    @Resource
    private VolunteerService volunteerService;

    @Resource
    private PetService petService;

    /**
     * 根据筛选条件查询机构列表
     *
     * @param mechanismScreen
     * @param pageable
     * @return
     */
    @Override
    public PageableDetails queryByScreen(MechanismScreen mechanismScreen, Pageable pageable) {
        //当前页
        Integer pageNum = pageable.getPageNumber();
        //每页条数
        Integer pages = pageable.getPageSize();

        //查询总条数
        Integer total = mechanismMapper.queryCount(mechanismScreen);
        if ("莆田市".equals(mechanismScreen.getCity())){
            mechanismScreen.setCity("");
            mechanismScreen.setCounty("");
            mechanismScreen.setProvince("");
        }
        if (total <= 0){
            mechanismScreen.setCity("");
            mechanismScreen.setCounty("");
            mechanismScreen.setProvince("");
        }
//        if (total == 0) {
//            ExceptionUtils.error(CommonCode.DATA_ERROR);
//        }
        //存储机构的列表
        List<MechanismList> mechanismList = new ArrayList<>();
        //特权
        if (!redisUtils.queryKey("Mechanism")) {
            //没有进入这里，不知都干嘛
            List<String> list = mechanismMapper.queryPower();
            redisUtils.setKey("Mechanism", list);
        }

        //从redis中取出机构 为空不用管
        List<String> m = redisUtils.getRedis("Mechanism");

        AtomicBoolean search = new AtomicBoolean(false);
        //一下代码没有走
        m.forEach(s -> {
            //如果位置相同
            if (s.equals(mechanismScreen.getCity())) {
                System.out.println(s);
                search.set(true);
            }
        });

        //存储机构的列表
        List<MechanismList> privilege = new ArrayList<>();
        //以下代码无用
        if (!search.get()) {
            //查询官方机构信息
            privilege = mechanismMapper.queryPrivilege();
            System.out.println(privilege);
        }

        //根据条件查询机构 有数据 数据有一条
        List<MechanismList> mechanisms = mechanismMapper.queryByScreen(mechanismScreen, pageNum * pages, pages);

        if (CollectionUtils.isEmpty(mechanisms) || mechanisms.size() < 10) {
           //进来的原因是只有一个机构

            //defaults未false说明是默认查询 没有走这里
            if (mechanismScreen.getDefaults()) {
                if (CollectionUtils.isEmpty(mechanisms)) {
                    ExceptionUtils.error(CommonCode.DATA_ERROR);
                } else {
                    int totalPages = PageUtils.returnPages(total, pageable.getPageSize());

                    List<MechanismByScreen> convert = iGenerator.convert(mechanisms, MechanismByScreen.class);
                    return new PageableDetails<>(pageNum, pages, total, totalPages, convert);
                }
            }


            MechanismScreen mechanismScreenNotSize = new MechanismScreen();
            //莆田被拷贝
            BeanUtils.copyProperties(mechanismScreen, mechanismScreenNotSize);

            int i = 1;
            //根据查询情况进行递减保证列表有值
            while (true) {
                switch (i) {
                    case 1:
                        mechanismScreen.setCounty("");
                        break;
                    case 2:
                        mechanismScreen.setCity("");
                        break;
                    case 3:
                        mechanismScreen.setProvince("");
                        break;
                    case 4:
                        mechanismScreen.setMeClass("");
                        break;
                }
                //如果我们填了莆田
                if (CollectionUtils.isEmpty(mechanismList))
                    mechanisms = mechanismMapper.queryByScreen(mechanismScreen, pageNum * pages, pages);
                else
                    mechanisms = mechanismMapper.queryByScreenNotSize(mechanismScreenNotSize, pageNum * pages, pages);
                if (!CollectionUtils.isEmpty(mechanisms) || i == 5) {
                    if (mechanisms.size() >= 9 || mechanismList.size() >= 10) {
                        total = total + mechanismMapper.queryCountNotSize(mechanismScreenNotSize);
                        mechanismList.addAll(mechanisms);
                        mechanisms.clear();
                        mechanisms = mechanismList;
                        break;
                    }
                }

                mechanismList.addAll(mechanisms);
                i++;
            }
        }

        if (CollectionUtils.isEmpty(mechanisms)) {
            ExceptionUtils.error(CommonCode.DATA_ERROR);
        }
        if (!search.get()) {
            mechanisms.addAll(0, privilege);
        }

        List<MechanismByScreen> convert = iGenerator.convert(mechanisms, MechanismByScreen.class);

        int totalPages = 0;
        if (total % pageable.getPageSize() != 0) {
            totalPages += 1;
        }
        totalPages += total / pageable.getPageSize();
        return new PageableDetails<>(pageNum, pages, total, totalPages, convert);
    }

    /**
     * 根据id查询机构公共信息
     *
     * @param id
     * @return
     */
    @Override
    public MechanismById queryById(Long id) {
        Mechanism mechanism = mechanismMapper.queryById(id);
        if (mechanism == null) {
            return null;
        }
        MechanismById mechanismById = new MechanismById();
        BeanUtils.copyProperties(mechanism, mechanismById);
        int count = petService.queryPlaceMeCount(id);
        if (count > 0) {
            mechanismById.setPlaceNum(count);
            mechanismById.setPlaceMechanism(petService.queryPlaceMe(id, 5));
        }
        return mechanismById;
    }

    /**
     * 查看申请义工机构选择列表
     *
     * @param pageable
     * @return
     */
    @Override
    public PageableDetails queryAllMechanism(Pageable pageable) {
        //当前页
        Integer pageNum = pageable.getPageNumber();
        //每页条数
        Integer pages = pageable.getPageSize();
        Integer total = mechanismMapper.queryALlMechanismCount();
        if (total == 0) {
            ExceptionUtils.error(CommonCode.DATA_ERROR);
        }
        List<MechanismVolunteer> mechanismVolunteers = mechanismMapper.queryAllMechanismAndVolunteer(pageNum, pages);
        int totalPages = 0;
        if (total % pageable.getPageSize() != 0) {
            totalPages += 1;
        }
        totalPages += total / pageable.getPageSize();
        return new PageableDetails<>(pageNum, pages, total, totalPages, mechanismVolunteers);
    }


    /**
     * 申请创建协会
     *
     * @param mechanismSing
     */
    @Override
    @Transactional
    public void creatMechanism(MechanismSing mechanismSing) {
        Integer existence = mechanismMapper.searchMechanismExistence(mechanismSing.getName());
        if (existence > 0) {
            ExceptionUtils.error(MechanismCode.CREATE_MECHANISM);
        }
        Long aLong = mechanismMapper.create(mechanismSing);
        if (aLong == null || aLong == 0) {
            ExceptionUtils.error(CommonCode.DATA_ERRORS);
        }
        mechanismMapper.MechanismDataSave(mechanismSing.getId());
        RoleUser roleUser = new RoleUser();
        roleUser.setId(mechanismSing.getUserId());
        roleUser.setRole(2);
        userFeiController.update_role(roleUser);

    }


    /**
     * 修改机构资料
     *
     * @param mechanismSing
     */
    @Override
    @Transactional
    public void updateMechanism(MechanismSing mechanismSing) {
        Integer row = mechanismMapper.updateMechanism(mechanismSing);
        if (row == 0) {
            ExceptionUtils.error(MechanismCode.UPDATE_MECHANISM);
        }
    }

    /**
     * 查看机构数据
     *
     * @param along
     * @return
     */
    @Override
    public MechanismData queryByData(Long along) {
        return mechanismDataMapper.queryById(along);
    }

    /**
     * 查看机构义工邀请二维码
     * @param aLong
     * @return
     */
    @Override
    public RqCode queryMechanism(Long aLong) {
        RqCode rqCode = imgFeiServer.queryRqCodeMe(aLong);
        if (rqCode == null) {
            ExceptionUtils.error(CommonCode.DATA_ERRORS);
        }
        return rqCode;
    }

    /**
     * 申请义工
     * @param volunteerCreate
     */
    @Override
    @Transactional
    public void createVolunteer(VolunteerCreate volunteerCreate) {
        String picture = mechanismMapper.queryByVolunteerId(volunteerCreate.getMe_id());
        if (StringUtils.isEmpty(picture)){
            ExceptionUtils.error(CommonCode.DATA_ERRORS);
        }
        volunteerCreate.setMePicture(picture);
        volunteerService.create(volunteerCreate);
        mechanismDataMapper.updateIn(VolunteerUntreated(volunteerCreate.getMe_id(),true,true));
    }

    /**
     * 删除义工
     * @param aLong
     * @param id
     */
    @Override
    public void deleteVolun(Long aLong, Long id) {
        volunteerService.deleteVolu(aLong,id);
    }


}
